package com.sc.exception;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.sc.app.restful.ExceptionResult;

@ControllerAdvice
public class CatchGlobalException extends ResponseEntityExceptionHandler {
    // 默认找error
    @ExceptionHandler(value = Exception.class)
    public ModelAndView errorHandler(HttpServletRequest request, HttpServletResponse response, Exception e)
            throws Exception {

        e.printStackTrace();
        if (isAjax(request)) {// 是ajax请求

            ExceptionResult rsp = new ExceptionResult("555", e.getMessage());
            ObjectMapper objectMapper = new ObjectMapper();
            String json = objectMapper.writeValueAsString(rsp);
            System.out.println(json);
            response.getOutputStream().write(json.getBytes("utf-8"));
            return null;
        } else {// 不是ajax请求
            ModelAndView mv = new ModelAndView();
            mv.addObject("exception", e);
            mv.addObject("url", request.getRequestURL());// 发生异常的路径
            mv.setViewName("error");// 指定发生异常之后跳转页面
            return mv;
        }
    }

    private boolean isAjax(HttpServletRequest request) {// 判断request是否是ajax请求
        return (request.getHeader("X-Requested-With") != null
                && "XMLHttpRequest".equals(request.getHeader("X-Requested-With").toString()));
    }
}
